<?php

namespace App\Controller\AdminApi\Trade;

use App\Base\Annotation\Common;
use App\Base\IRI;
use App\Base\BaseForm;
use App\Base\ActionBox\ActionBox;
use App\Base\SearchBox\SearchBox;
use App\Base\BaseController4Admin;
use Symfony\Component\Routing\Annotation\Route;

use App\Repository\Trade\OrderPackTradeRepository as Repository;
use App\Entity\Trade\OrderPackTrade as Entity;

/**
 * @Route("/admin/")
 */
class OrderPackTradeAdminApiController extends BaseController4Admin
{
    public $noDelete = [];
    public $entityName = "OrderPackTrade";
    public $limit = 100;
    public $listRow = ['createAt',"user.phone","product.name",'price','num','total','tips','status'];

    /**
     * @Route("OrderPackTrade/form",name="OrderPackTradeForm")
     */
    public function form(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $entity = $repository->find($data["id"]??0);
        $next = 0;
        $prev = 0;
        if (!$entity) {
            $entity = new Entity();
        }else{
            $qb = $repository->createQueryBuilder("A");
            createWhere($qb,["gt"=>["id"=>$data["id"]??0]]);
            $qb->setFirstResult(0)->setMaxResults(1);
            $qb->orderBy("A.id","ASC");
            $rst = $qb->getQuery()->execute();
            if (count($rst)==1) {
                if (isset($rst[0])) {
                    $next = $rst[0]->getId();
                }
            }
            $qb = $repository->createQueryBuilder("A");
            createWhere($qb,["lt"=>["id"=>$data["id"]??0]]);
            $qb->orderBy("A.id","DESC");
            $qb->setFirstResult(0)->setMaxResults(1);
            $rst = $qb->getQuery()->execute();
            if (count($rst)==1) {
                if (isset($rst[0])) {
                    $prev = $rst[0]->getId();
                }
            }
        }
        $BaseForm = new BaseForm(Entity::class);
        //表单选项
        $BaseForm->addEntity('product',"产品")->setName("ProductTrade")->setMulti(false)->getData();
        $BaseForm->addItem('price')->getData();
        $BaseForm->addItem('num')->getData();
        $BaseForm->addItem('total')->getData();
        $entity = $this->toArray($entity);
        $BaseForm->setEntity($entity);
        $data = array(
            "title" => "创建表单",
            "show"   => $BaseForm->createForm(),
            "isAdd"   => true,
            "next"   => $next,
            "prev"   => $prev,
        );
        return $this->json_out(1,"OK",$data);
    }

    /**
     * @Route("OrderPackTrade/submit",name="OrderPackTradeSubmit",methods={"POST"})
     */
    public function submit(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $entity = $repository->find($data["id"]?:0);
        if (!$entity) {$entity = new  Entity();}
        /**@var $OrderPackTrade Entity*/
        $OrderPackTrade = $this->updateEntity($data,Entity::class,$entity);
        $this->myEm()->persist($OrderPackTrade);$this->myEm()->flush();
        return $this->json_out(1,"保存成功","/admin/list/auto?en=".$this->entityName);
    }

    /**
     * @Route("OrderPackTrade/list",name="OrderPackTradeGetList")
     */
    public function getList(Repository $repository)
    {
        $this->needToBeAdmin();
        $data       = $this->getRequestData();
        $per_page   = $this->limit;
        $page       = $data["page"]??1;
        $where      = $data['_where']??[];
        $search     = $data['_search']??[];
        $order      = $data["_order"]??[];
        $statusArr = [
            ["id"=>0,"value"=>"未处理"],
            ["id"=>500,"value"=>"已发货"],
            ["id"=>90,"value"=>"取消/退单"]
        ];
        $phone = $data["phone"]??'';
        if ($phone) {
            $where['eq']["user.phone"] = $phone;
        }
        //列表筛选
        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,['user.phone',"user.name","product.name"],"or");
        createOrderBy($qb,$order);
        $qb->setFirstResult($page*$this->limit - $this->limit)->setMaxResults($this->limit);
        $list = $qb->getQuery()->execute();
        $this->setGroups("pack","prod","user");
        $list= $this->normalize($list);
        foreach ($list as &$row) {
            foreach ($statusArr as $item ) {
                if ($item["id"] == $row["status"]) {
                    $row["status"] = $item["value"];
                }
            }
        }

        //列表计数
        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,['user.phone',"user.name","product.name"],"or");
        $qb->select("count(A.id) as num");
        $total = $qb->getQuery()->execute()[0]["num"]??0;

        //表头数据和列表内展示形式
        $this->clearGroups();
        $config = getEntityAnnotationData(Entity::class);
        //额外数据示例
        //$config["KEY"] = (new Common())->setName("NAME")->setWidth("300");

        //设置筛选数据表单
        $sb = new SearchBox();
        $sb->setExcel(true);
        $sb->addSelect("status")->setHelpText("选择订单状态")->setChoices($statusArr)->createData();
        $sb->addText('user.phone')->setHelpText('用户手机号')->createData();
        $sb->addDate('createAt','gt')->setHelpText('下单时间A')->createData();
        $sb->addDate('createAt','lt')->setHelpText('下单时间B')->createData();
        $sb->addText('product.name')->setHelpText('产品名称')->createData();
        //设置筛选数据表单
        $ab = new ActionBox();
        $ab->addSelect('status')->setChoices(
            $statusArr
        )->setHelpText('修改状态')->createData();
        //todo 设置筛选数据
        $data = array(
            'en'     => "{$this->entityName}",
            'title'     => "列表",
            'header'     => $this->listRow,
            "config"    => $config,
            'lists'     => $list,
            'searchBox' => $sb->createData(),
            'actionBox' => $ab->createData(),
            "page"      =>['total'=>$total,"limit"=>$per_page,"page"=>$page*1],
        );
        return $this->json_out(1,'OK',$data);
    }

    /**
     * @Route("OrderPackTrade/OrderSum/list",name="OrderPackTradeGetOrderSumList")
     */
    public function OrderPackTradeGetOrderSumList(Repository $repository)
    {
        $this->needToBeAdmin();
        $data       = $this->getRequestData();
        $per_page   = $this->limit;
        $page       = $data["page"]??1;
        $where      = $data['_where']??[];
        $search     = $data['_search']??[];
        $order      = $data["_order"]??[];
        $order= [];
        $statusArr = [
            ["id"=>0,"value"=>"未处理"],
            ["id"=>500,"value"=>"已发货"],
            ["id"=>90,"value"=>"取消/退单"]
        ];
        //列表筛选
        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        createOrderBy($qb,$order);
        $qb->select("u.phone");
        $qb->addSelect("sum(A.num) as num ");
        $qb->addSelect("sum(A.total) as total ");
        $qb->join("A.user","u");
        $qb->addGroupBy("u.phone");
        $qb->setFirstResult($page*$this->limit - $this->limit)->setMaxResults($this->limit);
        $list = $qb->getQuery()->execute();
        foreach ($list as &$row) {
            $row["total"] = round($row["total"],2)." ";
        }

        //列表计数
        $qb = $repository->createQueryBuilder("A");
//        $qb->select("u.phone");
//        $qb->addSelect("sum(A.num) as num ");
//        $qb->addSelect("sum(A.total) as total ");
        $qb->join("A.user","u");
        $qb->addGroupBy("u.phone");
        createWhere($qb,$where);
        createSearch($qb,$search,['user.phone',"user.name","product.name"],"or");
        $qb->select("count(A.id) as num");
        $total = $qb->getQuery()->execute()[0]["num"]??0;

        //表头数据和列表内展示形式
        $this->clearGroups();
//        $config = getEntityAnnotationData(Entity::class);
        $config = [];
        //额外数据示例
        $config["phone"] = (new Common())->setName("手机号")->setWidth("300");
        $config["num"] = (new Common())->setName("下单总数")->setWidth("300");
        $config["total"] = (new Common())->setName("下单总金额")->setWidth("");

        //设置筛选数据表单
        $sb = new SearchBox();
        $sb->setExcel(false);
//        $sb->addText('product.name')->setHelpText('产品名称')->createData();
        $sb->addSelect("status")->setHelpText("选择订单状态")->setChoices($statusArr)->createData();
        $sb->addText('user.phone')->setHelpText('用户手机号')->createData();
        $sb->addDate('createAt','gt')->setHelpText('下单时间A')->createData();
        $sb->addDate('createAt','lt')->setHelpText('下单时间B')->createData();
        //设置筛选数据表单
        $ab = new ActionBox();
//        $ab->addSelect('status')->setChoices($statusArr)->setHelpText('修改状态')->createData();
        //todo 设置筛选数据
        $data = array(
            'en'     => "{$this->entityName}",
            'title'     => "列表",
            'header'     => ["phone","num","total"],
            "config"    => $config,
            'lists'     => $list,
            'searchBox' => $sb->createData(),
            'actionBox' => $ab->createData(),
            "page"      =>['total'=>$total,"limit"=>$per_page,"page"=>$page*1],
        );
        return $this->json_out(1,'OK',$data);
    }

    /**
     * @Route("OrderPackTrade/excel",name="OrderPackTradeGetListExcel")
     */
    public function getListExcel(Repository $repository)
    {
        $this->needToBeAdmin();
        $data       = $this->getRequestData();
        $where      = $data['_where']??[];
        $search     = $data['_search']??[];
        $order      = $data["_order"]??[];
        //列表筛选
        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,['user.phone',"user.name","product.name"],"or");
        createOrderBy($qb,$order);
        $list = $qb->getQuery()->execute();
        $this->setGroups("pack","prod","user");
        $list= $this->normalize($list);

//        dump($list);

        foreach ($list as &$row) {
            $row["user"] = "手机号：".$row["user"]["phone"]."";
            $row["product"] = $row["product"]["name"];
        }

        $config = getEntityAnnotationData(Entity::class);
        if (count($list)>0) {
            $row = $list[0];
            $title = [];
            foreach ($row as $key=>$value) {
                $title[] = isset($config[$key])?$config[$key]->cnName:"";
            }
        }else{
            $title=[
                "","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""
            ];
        }
        $this->excelOut($title,$list,"123.xls");
    }


    /**
     * @Route("OrderPackTrade/delete",name="OrderPackTradeDelete",methods={"POST"})
     */
    public function delete(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $ids = $this->getRequestData()["ids"]??[];
        foreach ($ids as $id) {
            if (in_array($id , $this->noDelete) || in_array(0 , $this->noDelete)) {continue;}
            if ($entity= $repository->find($id)) {$this->myEm()->remove($entity);}
        }
        $this->myEm()->flush();
        return $this->json_out(1,'删除成功');
    }


    /**
     * @Route("OrderPackTrade/action",name="OrderPackTradeAction",methods={"GET","POST"})
     */
    public function UserAction(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $ids = $this->getRequestData()["ids"]??[];
        $action = $this->getRequestData()["_action"]??[];
        //移除没有值的项
        foreach ($action as $key=>$value) {
            if ($value === "") {
                unset($action[$key]);
            }
        }
        foreach ($ids as $id) {
            if ($entity= $repository->find($id)) {
                $entity = $this->updateEntity($action,Entity::class,$entity);
                $this->myEm()->persist($entity);
            }
        }
        $this->myEm()->flush();
        return $this->json_out(1,'修改成功');
    }

    /**
     * @Route("OrderPackTrade/copy",name="OrderPackTradeCopy")
     */
    public function doCopy(Repository $repository)
    {
        $data = $this->getRequestData();
        if (!$entity = $repository->find($data["id"]??0)) {
            return $this->json_out(0,"数据丢失");
        }
        $tmp = $entity;
        $tmp = $this->toArray($tmp);
        $en = $this->serializer->denormalize($tmp,Entity::class);
        $this->myEm()->persist($en);$this->myEm()->flush();
        return $this->json_out(1,"复制成功");
    }


    /**
     * 用于entity组件窗口选择器
     * @Route("OrderPackTrade/search",name="OrderPackTradeGetList4EntitySelect")
     */
    public function getList4EntitySelect(Repository $repository)
    {
        $this->needToBeAdmin();
        $data = $this->getRequestData();
        $page = $data["page"]??1;
        $per_page   = $this->limit;
        $where = $data['_where']??[];
        $search = $data['_search']??[];
        $order = $data["_order"]??[];

        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        createOrderBy($qb,$order);
        $qb->setFirstResult($page*$this->limit - $this->limit)->setMaxResults($this->limit);
        $list = $qb->getQuery()->execute();
        $list= $this->normalize($list);

        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        $qb->select("count(A.id) as num");
        $total = $qb->getQuery()->execute()[0]["num"]??0;

        $this->clearGroups();
        $config = getEntityAnnotationData(Entity::class);
        $data = array(
            'en'     => "{$this->entityName}",
            'title'     => "列表",
            'header'     => $this->listRow,
            "config"    => $config,
            'lists'     => $list,
            "page"      =>['total'=>$total,"limit"=>$per_page,"page"=>$page*1],
        );
        return $this->json_out(1,'OK',$data);
    }


    /**
     * 用于ENTITY组件选项关展示
     * @Route("OrderPackTrade/viewer",name="OrderPackTradeList4EntityViewer")
     */
    public function OrderPackTradeList4EntityViewer(Repository $repository)
    {
        $data = $this->getRequestData();
        $id = $data["id"]??0;
        if (!is_array($id)) {
            $id = [$id];
        }
        $re = [];
        foreach ($id as $v) {
            //分别分成iri 和 id 两种方式
            $arr = myExplodeNumbers($v);
            $realId = array_pop($arr);
            $en = $repository->find($realId);
            if (!$en) {continue;}
            $re[] = [
                "id" => $en->getId(),
                "val" => $en->getName(),
            ];
        }
        return $this->json_out(1,"OK",$re);
    }

    /**
     * 用于列表组件List
     * @Route("OrderPackTrade/choice",name="OrderPackTradeList4ListChoice")
     */
    public function OrderPackTradeList4ListChoice(Repository $repository)
    {
        $all = $repository->findBy(array());
        foreach ($all as $en) {
            $re[] = [
                "id" => IRI::createIRIStringFromEntity(Entity::class,$en->getId()),
                "value" => $en->getName(),
            ];
        }
        return $this->json_out(1,"OK",$re);
    }
}
